package com.example.imageloaderdemo.adapter;

import android.content.Context;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;

import com.example.imageloaderdemo.imageloader.ImageLoader;
import com.example.imageloaderdemo.R;

import java.util.List;

/**
 * @author wdl
 */
public class ImageAdapter extends BaseAdapter {
    private List<String> mUrlList;
    private Context mContext;
    private boolean ifGridIdle = true;
    private ImageLoader mImageLoader;

    public void setIfGridIdle(boolean ifGridIdle) {
        this.ifGridIdle = ifGridIdle;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public ImageAdapter(Context context, List<String> mUrlList) {
        this.mUrlList = mUrlList;
        this.mContext = context;
        mImageLoader = ImageLoader.build(context);
    }

    @Override
    public int getCount() {
        return mUrlList.size();
    }

    @Override
    public Object getItem(int i) {
        return mUrlList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.grid_view_item, viewGroup, false);
            holder = new ViewHolder();
            holder.imageView = view.findViewById(R.id.image);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        ImageView imageView = holder.imageView;
        final String tag = (String) imageView.getTag();
        final String uri = (String) getItem(i);

        if (!uri.equals(tag)) {
            imageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_launcher_background,null));
        }

        //静止的时候加载
        if (ifGridIdle) {
            imageView.setTag(uri);
            int mImageWidth = imageView.getMeasuredWidth();
            mImageLoader.bindBitmap(uri, imageView, mImageWidth, mImageWidth);
        }
        return view;
    }

    class ViewHolder {
        ImageView imageView;
    }
}
